package chapter19;


import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import utils.ContextUtils;

import java.io.UnsupportedEncodingException;


/**
 * 发布订阅模式，spring提供接收消息的类
 */
public class Demo3 implements MessageListener {

    public static void main(String[] args) {
        RedisTemplate redisTemplate = ContextUtils.getBean("redisTemplate");
        String channel = "chat";
        redisTemplate.convertAndSend(channel,"I am lazy!!!");
    }

    @Override
    public void onMessage(Message message, byte[] bytes) {
        // 获取消息
        byte[] body = message.getBody();

        // 使用值序列化器转换
        RedisTemplate redisTemplate = ContextUtils.getBean("redisTemplate");
        String msgBody = (String) redisTemplate.getValueSerializer().deserialize(body);
        System.out.println(msgBody);

        //  获取channel
        byte[]  channel  =  message.getChannel();
        String channelStr = (String) redisTemplate.getStringSerializer().deserialize(channel);
        System.err.println(channelStr);

        // 渠道名称转换
        if (bytes !=null) {
            String bytesStr = null;
            try {
                bytesStr = new String(bytes, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            System.err.println(bytesStr);
        }
    }


}
